<template>
  <div id="main">
    <timerSelector
      ref="timerSelector"
      @dataChange="dataChange"
      @save="save"
      @reset="reset"
      mode="hexagram"
      :powerSixMembers="powerSixMembers"
      :highlights="monthAndDateHighlights"
      @highlightChange="highlightChange"
    ></timerSelector>

    <div class="content">
      <diagram
        :diagram="hostDiagram"
        :symbols="hostSymbols"
        :sixMembers="hostSixMembers"
        :noUse="hostNoUse"
        :each="hostDiagramEachOther.each"
        :other="hostDiagramEachOther.other"
        :highlights="highlights"
        :decoration="hostDecoration"
        :showTip="true"
      ></diagram>

      <diagram style="width: 38%"
        :diagram="mainDiagram"
        v-model="symbols"
        @input="refreshSymbol"
        :lock="lock"
        :sixMembers="mainSixMembers"
        :sixGods="mainSixGods"
        :each="mainDiagramEachOther.each"
        :other="mainDiagramEachOther.other"
        :editable="true"
        :highlights="highlights"
        :decoration="mainDecoration"
        :showTip="true"
      ></diagram>

      <diagram
        :diagram="changeDiagram"
        :symbols="changeSymbols"
        :sixMembers="changeSixMembers"
        :each="changeDiagramEachOther.each"
        :other="changeDiagramEachOther.other"
        :noUse="changeNoUse"
        :highlights="highlights"
        :decoration="changeDecoration"
        :showTip="true"
      ></diagram>
    </div>
  </div>
</template>

<script>
import * as consts from "../core/consts";
import core from "../core/core";

import timerSelector from "./timerSelector.vue";
import diagram from "./diagram.vue";
import { EventBus } from "../core/event-bus";
import showMessage from "./messageBox";
import getGodEvil from "../core/god-evil";
import changeMean from "../core/change-mean";



export default {
  name: "hexagram",
  data() {
    return {
      id: this.$global.db.generateId(),
      symbols: [],
      mainDiagram: null,
      mainDiagramEachOther: {},
      mainSixGods: [],
      mainSixMembers: [],
      mainDecoration: [], //分析月破、日破、旬空的cssClass
      hostDiagram: null,
      hostDiagramEachOther: {},
      hostSymbols: [],
      hostSixMembers: [],
      hostDecoration: [],
      changeSymbols: [],
      changeDiagram: null,
      changeSixMembers: [],
      changeDiagramEachOther: {},
      changeDecoration: [],
      lock: false,
      tableName: "hexagrams",
      powerSixMembers: {
        month: {},
        date: {},
        dead: [{}, {}],
      },
      highlights: [],
      highlight: "",
      // monthBranch: "",
      // date: "",
    };
  },
  computed: {
    hostNoUse() {
      const ret = [];
      for (let i = 0; i < this.hostSixMembers.length; i++) {
        if (
          this.mainSixMembers.find(
            (x) => x.sixMember.name == this.hostSixMembers[i].sixMember.name
          )
        )
          ret.push(i);
      }
      return ret;
    },
    changeNoUse() {
      const ret = [];

      for (let i = 0; i < this.symbols.length; i++) {
        if (this.symbols[i] == 7 || this.symbols[i] == 8) ret.push(i);
      }
      return ret;
    },
    diagramBranchNames() {
      return this.mainSixMembers
        .map((x) => x.earthBranch.name)
        .concat(
          this.hostSixMembers
            .filter((x, index) => !this.hostNoUse.includes(index))
            .map((x) => x.earthBranch.name)
        )
        .concat(
          this.changeSixMembers
            .filter((x, index) => !this.changeNoUse.includes(index))
            .map((x) => x.earthBranch.name)
        );
    },

    

    monthAndDateHighlights() {
      const ret = {};

      const monthAndDateBranchNames = this.getMonthAndDateBranchNames();
      const relation = consts.relation[this.highlight];
      if(relation){
        let factorsMaxLength = 0;
        relation.forEach(item => {
          if(item.factors.length > factorsMaxLength)
            factorsMaxLength = item.factors.length;
        });
        if(factorsMaxLength> 2){
          ret.month = this.computeHighlights(monthAndDateBranchNames);
          ret.date = this.computeHighlights(monthAndDateBranchNames);
        }
        else{
          ret.month = this.computeHighlights(monthAndDateBranchNames[0]);
          ret.date = this.computeHighlights(monthAndDateBranchNames[1]);
        }
      }
      

      return ret;

    
    }
  },
  methods: {
    dataChange(data) {
      // this.monthBranch = data.month ? data.month[1] : "";
      // this.date = data.date;
      this.refreshSymbol();
      
    },

    refreshSymbol() {
      const mainDiagram = core.getDiagram(this.symbols);


      this.mainDiagramEachOther = core.getEachOther(mainDiagram);

      this.mainSixGods = core.getSixGods(this.$refs.timerSelector.date);
      this.mainSixMembers = core.getSixMembers(mainDiagram);

      const hostDiagram = consts.sixtyFourDiagrams[mainDiagram.host.name];
      this.hostSixMembers = core.getSixMembers(hostDiagram);
      this.hostDiagramEachOther = core.getEachOther(hostDiagram);
      this.hostSymbols = hostDiagram.bottom.symbols
        .concat(hostDiagram.top.symbols)
        .map((x) => (x ? 7 : 8));

      this.changeSymbols = core.changeDiagram(this.symbols);
      const changeDiagram = core.getDiagram(this.changeSymbols);
      this.changeSixMembers = core.getSixMembers(
        changeDiagram,
        hostDiagram.host.element
      );
      this.changeDiagramEachOther = core.getEachOther(changeDiagram);


      this.mainDiagram = mainDiagram;
      this.hostDiagram = hostDiagram;
      this.changeDiagram = changeDiagram;

      //给月令，日令，空亡安排六亲

      const powerSixMembers = { month: {},
        date: {},
        dead: [{}, {}]};

      if (
        this.$refs.timerSelector.month &&
        this.$refs.timerSelector.month.length == 2
      )
        powerSixMembers.month.sixMember = core.getSixMember(
          hostDiagram.top.element,
          consts.earthBranches[this.$refs.timerSelector.month[1]].element
        ).name;
      if (
        this.$refs.timerSelector.date &&
        this.$refs.timerSelector.date.length == 2
      )
        powerSixMembers.date.sixMember = core.getSixMember(
          hostDiagram.top.element,
          consts.earthBranches[this.$refs.timerSelector.date[1]].element
        ).name;
      if (
        this.$refs.timerSelector.dead &&
        this.$refs.timerSelector.dead.length == 2
      ) {
        powerSixMembers.dead[0].sixMember = core.getSixMember(
          hostDiagram.top.element,
          consts.earthBranches[this.$refs.timerSelector.dead[0]].element
        ).name;
        powerSixMembers.dead[1].sixMember = core.getSixMember(
          hostDiagram.top.element,
          consts.earthBranches[this.$refs.timerSelector.dead[1]].element
        ).name;
      }

      this.highlights = this.computeHighlights(this.getMonthAndDateBranchNames());
     

      if(this.$refs.timerSelector){
        //先计算每个爻对日月的旺衰值
        core.computeHexagramRate(this.mainSixMembers, [], this.$refs.timerSelector.month[1], this.$refs.timerSelector.date[1]);
        core.computeHexagramRate(this.hostSixMembers,  [], this.$refs.timerSelector.month[1], this.$refs.timerSelector.date[1]);
        core.computeHexagramRate(this.changeSixMembers, [], this.$refs.timerSelector.month[1], this.$refs.timerSelector.date[1]);

        // core.computeHexagramRate(this.hostSixMembers,  this.hostNoUse, this.$refs.timerSelector.month[1], this.$refs.timerSelector.date[1]);
        // core.computeHexagramRate(this.changeSixMembers, this.changeNoUse, this.$refs.timerSelector.month[1], this.$refs.timerSelector.date[1]);


        //根据上一步的旺衰值计算日破、月破、暗动等
        this.mainDecoration = core.getDecoration(this.mainSixMembers, this.symbols, [], this.$refs.timerSelector.month[1], this.$refs.timerSelector.date[1], this.$refs.timerSelector.dead);
        this.hostDecoration = core.getDecoration(this.hostSixMembers, this.hostSymbols, this.hostNoUse, this.$refs.timerSelector.month[1], this.$refs.timerSelector.date[1], this.$refs.timerSelector.dead);
        this.changeDecoration = core.getDecoration(this.changeSixMembers, this.changeSymbols, this.changeNoUse, this.$refs.timerSelector.month[1], this.$refs.timerSelector.date[1], this.$refs.timerSelector.dead);

        this.mainSixMembers.godEvil = getGodEvil({
          year: this.$refs.timerSelector.year,
          month: this.$refs.timerSelector.month,
          date: this.$refs.timerSelector.date,
          time: this.$refs.timerSelector.time
          }, this.mainDiagramEachOther.each, this.symbols[this.mainDiagramEachOther.each]);

        this.hostSixMembers.godEvil = getGodEvil({
          year: this.$refs.timerSelector.year,
          month: this.$refs.timerSelector.month,
          date: this.$refs.timerSelector.date,
          time: this.$refs.timerSelector.time
          });
        this.changeSixMembers.godEvil = this.hostSixMembers.godEvil;

        //本次变化的含义，化进，化退，回头生，回头克
        changeMean(this.mainSixMembers, this.changeSixMembers, this.symbols);
        
        //日月对应的神煞
        powerSixMembers.month.godEvil = this.mainSixMembers.godEvil[this.$refs.timerSelector.month[1]];
        powerSixMembers.date.godEvil = this.mainSixMembers.godEvil[this.$refs.timerSelector.date[1]];
        powerSixMembers.dead[0].godEvil = this.mainSixMembers.godEvil[this.$refs.timerSelector.dead[0]];
        powerSixMembers.dead[1].godEvil = this.mainSixMembers.godEvil[this.$refs.timerSelector.dead[1]];

        this.powerSixMembers = powerSixMembers;


      }

      
    },

    save() {
      const data = {
        id: this.id,
        owner: this.$parent.$refs.headerView.owner,
        question: this.$parent.$refs.headerView.question,
        year: this.$refs.timerSelector.year,
        month: this.$refs.timerSelector.month,
        date: this.$refs.timerSelector.date,
        time: this.$refs.timerSelector.time,
        createDatetime: this.$refs.timerSelector.createDatetime,
        symbols: this.symbols,
        mainDiagram: core.getDiagramName(this.mainDiagram),
        changeDiagram: core.getDiagramName(this.changeDiagram),
        remark: this.$parent.$refs.headerView.remark
      };
      this.$global.db.save(this.tableName, data, true, () => {
        this.$refs.timerSelector.saveSuccess();
      });
      // showMessage("保存成功");
    },
    reset(command) {
      if(command == "clear"){
        this.$parent.$refs.headerView.owner = "";
        this.$parent.$refs.headerView.question = "";
        this.$parent.$refs.headerView.remark = "";
        this.symbols = core.randomSymbols();
        this.refreshSymbol();
      }
      else(command == "reset")
        this.id = this.$global.db.generateId();
    },
    loadDiagram(data) {
      this.id = data.id;
      this.symbols = data.symbols;
      this.$refs.timerSelector.datetimeChange();
      this.refreshSymbol();
    },
    highlightChange(highlight) {
      this.highlight = highlight;
      this.highlights = this.computeHighlights(this.getMonthAndDateBranchNames());
    },
    computeHighlights(monthOrDateBranchNames) {

      let allBranches = this.diagramBranchNames;

      allBranches = allBranches.concat(monthOrDateBranchNames);

      allBranches = [...new Set(allBranches)];


      const highlights = new Set();
      //测试relation
      if (this.highlight) {
        for (const item of consts.relation[this.highlight]) {
          if (item.factors.every((x) => allBranches.includes(x.name)))
            highlights.add(item);
        }
      }
      return [...highlights];
    },
    getMonthAndDateBranchNames() {
      const allBranches = [];
      
      if (this.$refs.timerSelector) {
        if (this.$refs.timerSelector.month){
          allBranches.push(this.$refs.timerSelector.month[1]);
        }
        if (this.$refs.timerSelector.date)
          allBranches.push(this.$refs.timerSelector.date[1]);
      }
      return allBranches;
    },
  },
  mounted() {
    this.symbols = core.randomSymbols();
    this.$refs.timerSelector.datetimeChange();
    EventBus.$on("hexagrams-load-diagram", (data) => {
      this.loadDiagram(data);
    });
    EventBus.$on("lock", (x) => (this.lock = x));
  },
  components: {
    timerSelector,
    diagram,
  },
};
</script>

<style lang="scss" scoped>
#main {
  flex-direction: column;
  flex: 1;
}
.content {
  flex: 1;
  display: flex;
  justify-content: space-around;
  box-shadow: 0px 0px 10px rgba($color: #000000, $alpha: 0.1);
  background: var(--content-bg-color);
  margin: 0 4vmin;
  border-radius: 10px;
  padding: 2vmin 4vmin 0vmin 0;
}
</style>
